define(["Zepto", 
        "underscore", 
        "Backbone", 
        "Handlebars",  
        "text!templates/teacher/addcourse.html",
        "models/orariocorso",
        "models/corso",
        "collections/aulacollection",
        "views/common/menuview"
], function($, _, Backbone, Handlebars, template, OrarioCorso, Corso, AulaCollection, MenuView) {
	
    var lectureschedule;
    var AddCourse = Backbone.View.extend({

        template : Handlebars.compile(template),

        render: function(eventName) {
            this.$el.html(this.template(this.model.toJSON()));
            
			// menu top
			this.menutop = new MenuView({
				el : $('#menu', this.el),
				model : this.model
			});
			this.menutop.render();

            //alert('facolta2:' + this.model.get('corsolaurea').facolta.objectId);

            var aulee = new AulaCollection();
            aulee.fetch({
                query : {
                    facolta: {"__type":"Pointer","className":"facolta","objectId":this.model.get('facolta').objectId}
                },
                success: function(data) {
                    aulee.each(
                        function(aula) {
                            $('.aula').append('<option value="' + aula.get('objectId') + '">' + aula.get('nome') + '</option>');
                        });
                    $('.aula').children('option').first().html('');
                    $('.aula').removeAttr('disabled');
                    lectureschedule = $('.lectureschedule').last().clone();
                    $('.day').scroller({
                        preset: 'select',
                        theme: 'android-ics light',
                        display: 'modal',
                        mode: 'scroller',
                    });

                    $('.time').scroller({
                        preset: 'time',
                        theme: 'android-ics light',
                        display: 'modal',
                        mode: 'scroller',
                        timeFormat: 'HH:ii',
                        timeWheels: 'HHii',
                        stepMinute: 15
                    });
                    $('.aula').scroller({
                        preset: 'select',
                        theme: 'android-ics light',
                        display: 'modal',
                        mode: 'scroller'
                    });
                }
            });
            return this;  
        },

        // postRender: function(eventName) {
        // },

        events: {
            'click #create': 'addCourse',
            'click #plus': 'moreSchedule',
            'click #minus': 'lessSchedule',
            'touchstart .button': 'over',
            'touchend .button': 'left',
            'touchcancel .button': 'left',
            'touchstart button': 'over',
            'touchend button': 'left',
            'touchcancel button': 'left',
            
        },


        addCourse: function(event) {
        	
        	// id del docente
        	// var docent_id = this.model.get('objectId');
        	// //alert('id ' + docent_id);
            
            var nome1 = $('input.nomecorso').val();
            if(nome1 == ""){alert('inserire il nome del corso'); return;}
            var cfu1 = $('input.cfu').val();
            if(cfu1 == ""){alert('inserire i CFU del corso'); return;}
            var sillabo1 = $('textarea.big').val();
            if(sillabo1 == ""){alert('inserire il sillabo del corso'); return;}
            var testi1 = $('textarea.small').val();
            if(testi1 == ""){alert('inserire i testi del corso'); return;}

            
            // crea Corso
            // tutti i campi devono essere diversi da null
            var corso = new Corso();

            var testi2 = "";
            var testiArray = testi1.split('\n');
            while(testiArray.length) {
                testi2 += "<li>" + testiArray.shift() + "</li>";
            }

            var sillabo2 = "";
            var sillaboArray = sillabo1.split('\n');
            while(sillaboArray.length) {
                sillabo2 += "<li>" + sillaboArray.shift() + "</li>";
            }
            
            corso.save({
                    nome: nome1,
                    cfu: parseInt(cfu1),
                    sillabo: sillabo2,
                    testi: testi2,
                    isattivo: true,
                    docente: {"__type":"Pointer","className":"_User","objectId":this.model.get('objectId')},
                    corsolaurea: {"__type":"Pointer","className":"corsolaurea","objectId":this.model.get('corsolaurea').objectId}

                },{
                error: function(error){ alert('Error'); },

                success: function(model, resp){
                	//alert('Corso creato: ' + resp.objectId);
                	
                	$('.lectureschedule').each(function(index, element){
                        //alert('Orario n.' + index +':' + $(this).children('.time.ora1').val() +'-' + $(this).children('.time.ora2').val() );
                        var orainizioArray = $(this).children('.time.ora1').val().split(':');
                        var orainizio = parseInt(orainizioArray[0]) + parseInt(orainizioArray[1])/60;
                        
                        var orafineArray = $(this).children('.time.ora2').val().split(':');
                        var orafine = parseInt(orafineArray[0]) + parseInt(orafineArray[1])/60;

                        //alert($(this).children('.day').val() + '  ' + orainizio + ' - ' + orafine);

                        var orario = new OrarioCorso({
                            orainizio: orainizio,
                            orafine: orafine,
                            weekday: $(this).children('.day').val(),
                            corso: {"__type":"Pointer","className":"corso","objectId":resp.objectId},
                            aula: {"__type":"Pointer","className":"aula","objectId":$(this).children('.aula').val()}
                        });
                        orario.save({
                            success: function(error) { alert('Orario salvato'); },
                            error: function(model, resp) { alert('Errore salvataggio orario'); }
                        });

                    });
                    alert('Corso creato');
                    
                }});
            
        },

        moreSchedule: function(event){
            newlectureschedule = lectureschedule.clone();
            newlectureschedule.children('.day').scroller({
                preset: 'select',
                theme: 'android-ics light',
                display: 'modal',
                mode: 'scroller'
            });
            newlectureschedule.children('.time').scroller({
                preset: 'time',
                theme: 'android-ics light',
                display: 'modal',
                mode: 'scroller',
                timeFormat: 'HH:ii',
                timeWheels: 'HHii',
                stepMinute: 15
            });
            newlectureschedule.children('.aula').scroller({
                preset: 'select',
                theme: 'android-ics light',
                display: 'modal',
                mode: 'scroller'
            });

            $('.lectureschedule').last().after(newlectureschedule);
        },

        lessSchedule: function(event){
            $('.lectureschedule').eq(-2).next('.lectureschedule').remove();
        },

        over: function(event) {
            $(event.currentTarget).addClass('fake-active');
        },

        left: function(event) {
            $(event.currentTarget).removeClass('fake-active');
        }
    });

    return AddCourse;

});
